import { Inject, Injectable, OnModuleInit, Scope, UnauthorizedException } from "@nestjs/common";
import { CreateUserDto, LoginDto, RegisterDto } from "src/dto/create-user.dto";
import { UpdateUserDto, SaveTokenDto, ChangePassword, ChangePhone, ForgotDto } from "src/dto/update-user.dto";
import { InjectRepository } from "@nestjs/typeorm";
import { In, IsNull, Not, Repository } from "typeorm";
import { User } from "src/entity/user.entity";
import { ResponseResult } from "src/utils/response.result"; // 确保路径正确
import { JwtService } from "@nestjs/jwt";
import { hashPassword, validatePassword } from "../utils/bcryptUtils";
import { UserRole } from "src/entity/user-role.entity";
import { CACHE_MANAGER } from "@nestjs/cache-manager";
import { Cache } from 'cache-manager';
import { REQUEST } from "@nestjs/core";


@Injectable({ scope: Scope.REQUEST })
export class UserService {

  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private jwtService: JwtService,

    @InjectRepository(UserRole)
    private userRoleRepository: Repository<UserRole>,

    @Inject(REQUEST) private readonly request: Request,
    // 注入缓存
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
  ) {

    // try {
    //   // 尝试获取JWT配置信息，验证是否加载正确
    //   const config = jwtService;
    //   console.log("JwtService initialized with config:", config);
    // } catch (error) {
    //   console.error("Failed to initialize JwtService", error);
    // }
  }

  /**
   * 
   * @param page 
   * @param limit 
   * @param request 
   * @param keyword 
   * @returns 
   */
  async findAll(page: number, limit: number, request: Request, keyword: string): Promise<any> {
  }

  /**
   * 
   * @param loginDto 
   * @returns 
   */
  async login(loginDto: LoginDto) {
    // 校验是用户名还是邮箱
    const isEmail = /^\S+@\S+\.\S+$/.test(loginDto.userName);
    const result = await this.usersRepository.findOneBy(isEmail ? { email: loginDto.userName } : { userName: loginDto.userName });

    if (!result) {
      return ResponseResult.errorResult("账号不存在！请注册");
    }

    // 验证密码
    if (!await validatePassword(loginDto.password, result.password)) {
      return ResponseResult.errorResult("密码错误");
    }

    const payload = { sub: result.id, userName: result.userName };
    // const token = await this.jwtService.signAsync(payload);
    const token = null

    return ResponseResult.okResult("登录成功", token);
  }

  // 注册
  /**
   * 
   * @param registerDto 
   * @returns 
   */
  async register(registerDto: RegisterDto) {
    // 先查询是否账号存在
    const userByUsername = await this.usersRepository.findOneBy({ userName: registerDto.userName });
    if (userByUsername) {
      return ResponseResult.errorResult("用户名已存在！请重新输入");
    }

    // 查询是否邮箱已被注册
    // const userByEmail = await this.usersRepository.findOneBy({ email: registerDto.email });
    // if (userByEmail) {
    //   return ResponseResult.errorResult("邮箱已被注册！请重新输入");
    // }

    // const configs: Config[] = await this.cacheManager.get<Config[]>('configs') || [];

    // 检查 mail status 是否为 0
    // const mailStatus: any = configs.find(config => config.type == 'mail' && config.key == 'status')?.value;

    // if (mailStatus == 0) {
    // 如果邮箱功能未开启，直接跳过验证码逻辑，进入注册流程
    // return await this.completeRegistration(registerDto);
    // }

    // // 处理验证码逻辑
    // if (!registerDto.code) {
    //   const code = await this.generateRandomCode();
    //   // 存入缓存
    //   await this.cacheManager.set(`register_verify_${registerDto.email}`, code, 1800000);

    //   // 获取配置
    //   const name = configs.find(config => config.type == 'site' && config.key == 'title')?.value || 'Sugarless';
    //   // 发送验证码到邮箱
    //   await this.mailService.sendEmail(registerDto.email, `${code} 是你的 ${name} 验证码`, 'register', { code });
    //   return ResponseResult.okResult("验证码已发送到您的邮箱中");

    // } else {
    //   // 验证码校验
    //   let code = await this.cacheManager.get<string>(`register_verify_${registerDto.email}`);
    //   if (registerDto.code != code) {
    //     return ResponseResult.errorResult("验证码错误");
    //   }
    //   // 删除验证码
    //   await this.cacheManager.del(`register_verify_${registerDto.email}`);
    // }

    // 验证成功后进入注册
    // 密码加密
    registerDto.password = await hashPassword(registerDto.password);

    // 存入数据库
    const newUser = this.usersRepository.create(registerDto);
    const save = await this.usersRepository.save(newUser);

    return ResponseResult.okResult("注册成功", save);
  }

  /**
   * 
   * @param CreateUserDto 
   * @returns 
   */
  async create(CreateUserDto: CreateUserDto) {
  }

  /**
   * 
   * @param id 
   * @param request 
   * @returns 
   */
  async findOne(id: number, request: Request): Promise<any> {
  }
  /**
   * 
   * @param id 
   * @param updateUserDto 
   * @param request 
   * @returns 
   */
  async update(id: number, updateUserDto: UpdateUserDto, request: Request) {
  }

  /**
   * 
   * @param changePassword 
   * @param request 
   * @returns 
   */
  async updatePassword(changePassword: ChangePassword, request: Request) {
    const userId = request["user"]?.sub || null;
    const user = await this.usersRepository.findOneBy({ id: userId });
    // 检查旧密码是否正确
    if (!await validatePassword(changePassword.oldPassword, user.password)) {
      return ResponseResult.errorResult("密码错误！");
    }

    // 加密新密码
    const hashedPassword = await hashPassword(changePassword.newPassword);
    await this.usersRepository.update(userId, { password: hashedPassword });
    return ResponseResult.okResult("修改成功");
  }

  /**
   * 
   * @param id 
   * @returns 
   */
  async remove(id: number): Promise<any> {
    await this.usersRepository.delete(id);
    return ResponseResult.okResult("删除成功");
  }

  //   批量插入
  /**
   * 
   * @param list 
   * @returns 
   */
  async saveBatch(list: User[]) {
    await this.usersRepository.save(list);
    return ResponseResult.okResult("批量插入成功");
  }

}



